import { defineStore } from "pinia";
import {
  login,
  loginByUkey,
  getInfo,
  loginBySsoClientIp,
  loginBySsoCode,
  loginBySsoToken,
  loginBySso,
  goBacklogBySecretKey,
  loginByMsg,
  logoutBySsoCode,
  loginBySsoClientId,
} from "../api/login";
import {
  getDbsxNum,
  getEmailList,
  getHtglNum,
  getNetWorkNum,
  getGxglNum,
} from "../api/module/grbg/todoList";
import { getSetting } from "../api/common/notion";
import { zddk } from "../api/module/kqgl/kqgl";
import {
  getToken,
  setToken,
  removeToken,
  setSSOToken,
  removeSSOToken,
  getSSOToken,
} from "../utils/auth";
import websocket from "../utils/websocket";
import BlogMessage from "../components/Message/index";
import { getCs } from "../api/system/csgl/cszc";
import Cookies from "js-cookie";
import { EventBus } from "../components/HCEventBus/eventBus";

let timgerId = null;

function starTimer(callBack) {
  clearInterval(timgerId);
  callBack();
  timgerId = setInterval(() => {
    callBack();
  }, 60000);
}

export const useUserStore = defineStore("user", {
  state: () => ({
    token: getToken(),
    currentPostUnid: null,
    roles: [],
    info: {},
    // 待办数量
    totalBacklogCount: 0,
    // 上一次网络消息弹窗组件
    lastNetMessageCom: null,
    // 已办数量
    totalYbsxCount: 0,
    // 未读邮件数量
    totalEmaillogCount: 0,
    // 未读消息数量
    totalNetMessageCount: 0,
    // 当前选择的机构
    currentOrgUnid: null,
    // 阅文意见修改设置
    ywyjxgSetting: {},
  }),
  actions: {
    setToken(token) {
      if (token) {
        setToken(token);
        this.token = token;
      } else {
        removeToken();
        this.token = null;
      }
    },
    setCurrentPost(P_PostUnid) {
      if (P_PostUnid) {
        this.currentPostUnid = P_PostUnid;
        localStorage.setItem("postUnid_" + this.info.unid, P_PostUnid);
      } else {
        this.currentPostUnid = null;
        localStorage.removeItem("postUnid_" + this.info.unid);
      }
    },
    setRoles(roles) {
      this.roles = roles;
    },
    setInfo(info) {
      if (info) {
        localStorage.setItem("info", JSON.stringify(info));
        this.info = info;
      } else {
        localStorage.removeItem("info");
        this.info = {};
      }
    },
    setEmailNum(totalEmaillogCount) {
      this.totalEmaillogCount = totalEmaillogCount || 0;
    },
    setNetMessageNum(totalNetMssageCount) {
      this.totalNetMessageCount = totalNetMssageCount || 0;
    },
    setLastNetMessageCom(P_LastMessageCom) {
      this.lastNetMessageCom = P_LastMessageCom;
    },
    setDbsxNum(totalBacklogCount) {
      this.totalBacklogCount = totalBacklogCount || 0;
    },
    setYbsxNum(value) {
      this.totalYbsxCount = value || 0;
    },
    setAvatar(value) {
      this.info.avatar = value;
    },
    setCurrentOrgUnid(value) {
      if (value) {
        this.currentOrgUnid = value;
        localStorage.setItem("orgUnid_" + this.info.unid, value);
      } else {
        this.currentOrgUnid = null;
        localStorage.removeItem("orgUnid_" + this.info.unid);
      }
    },
    setYwyjxgSetting(value) {
      this.ywyjxgSetting = value;
    },
    // 登录
    async Login(userInfo) {
      try {
        const res = await login(userInfo);
        this.setToken(res.token);
        return res;
      } catch (error) {
        throw error;
      }
    },
    // 短信验证码登录
    async loginByMsg(userInfo) {
      try {
        const res = await loginByMsg(userInfo);
        this.setToken(res.token);
        return res;
      } catch (error) {
        throw error;
      }
    },
    // uKey登录
    async LoginByUkey(P_Data) {
      try {
        const res = await loginByUkey(P_Data);
        this.setToken(res.token);
        return res;
      } catch (error) {
        throw error;
      }
    },
    // 第三方认证登录
    async LoginByCode(data) {
      try {
        const response = await loginBySsoCode(data);
        this.setToken(response.token || response.data.token);
        setSSOToken(response.access_token || response.data.access_token);
        return response;
      } catch (err) {
        throw err;
      }
    },
    // 第三方认证登录 更加token
    async loginByToken(data) {
      try {
        const response = await loginBySsoToken(data);
        this.setToken(response.token || response.data.token);
        setSSOToken(response.access_token || response.data.access_token);
        return response;
      } catch (err) {
        throw err;
      }
    },
    // 第三方认证登录
    async LoginByClientIp(data) {
      try {
        const response = await loginBySsoClientIp(data);
        this.setToken(response.token || response.data.token);
        setSSOToken(response.access_token || response.data.access_token);
        return response;
      } catch (err) {
        throw err;
      }
    },
    // 菏泽单点登录
    async LoginByClientId(data) {
      try {
        const response = await loginBySsoClientId(data);
        this.setToken(response.token || response.data.token);
        setSSOToken(response.access_token || response.data.access_token);
        return response;
      } catch (err) {
        throw err;
      }
    },
    // 菏泽临时门户账号密码登录
    async HzLoginByPassword(data) {
      try {
        const res = await getCs("xtsz_decode_password");
        let isBtoaPassWord = false;
        if (res.result && res.result.defauleValues == 1) {
          isBtoaPassWord = true;
        }
        let loginData = {
          username: data.username,
          password: isBtoaPassWord ? window.btoa(data.password) : data.password,
        };
        return await this.Login(loginData);
      } catch (e) {
        throw e;
      }
    },
    // 用户名加密方式登录
    async LoginBySSO(data) {
      try {
        const response = await loginBySso(data);
        this.setToken(response.token);
        return response;
      } catch (err) {
        throw err;
      }
    },
    // 跳转待办
    async GoBacklogBySecretKey(data, params) {
      try {
        const response = await goBacklogBySecretKey(data);
        this.setToken(response.token);
        // 这里需要引入路由实例来进行跳转
        // 假设已经在某个地方引入了路由实例 router
        // router.push(params);
        return response;
      } catch (err) {
        throw err;
      }
    },
    // 更新内容日志
    async updateGxrz(showMessage) {
      const res = await getGxglNum();
      console.log(res, "更新内容");
      if (res.result) {
        BlogMessage({
          msg: "更新内容: " + res.result.remark,
          title: "更新提示",
          event: null,
          url: "/gxgl/gxglck",
          gxjlunid: res.result.unid,
        });
      }
    },
    // 更新合同管理数量
    async updateHtglNum(showMessage) {
      const res = await getHtglNum();
      console.log(this.info, "人员信息");
      let isHtts = Cookies.get("isHtts") || false;
      if (!isHtts) {
        isHtts = true;
        console.log(isHtts, "isHtts");
        if (res.result) {
          Object.keys(res.result).forEach((key) => {
            if (key === this.info.unid) {
              BlogMessage({
                msg:
                  "您有" + res.result[key] + "条合同需要线下归档，请及时处理",
                title: "消息提醒",
                event: null,
                url: "",
              });
            }
          });
        }
      }
    },
    // 更新待办数量
    async updateDbsxNum(showMessage) {
      const res = await getDbsxNum();
      let isTs = Cookies.get("isTs") || false;
      this.setDbsxNum(res.result.dbsl);
      if (!isTs && window.HC_config.VUE_APP_BACKLOGTIP) {
        isTs = true;
        Cookies.set("isTs", isTs);
        if (res.result.dbsl > 1 && showMessage) {
          BlogMessage({
            msg: "您有" + res.result.dbsl + "条待办消息，请注意查收",
            title: "消息提醒",
            event: null,
            url: "/dbsxgl/dbsx",
          });
        }
      }
      this.setYbsxNum(res.result.ybsl);
    },
    // 更新邮件数量
    async updateEmailNum() {
      const { result } = await getEmailList();
      result && this.setEmailNum(result.count);
    },
    // 获取用户信息
    async GetInfo() {
      // 开启websock 消息实时获取功能
      if (window.HC_config && window.HC_config.VUE_OPEN_WEBSOCKET) {
        websocket.closeWebSocket();
        websocket.initWebSocket(this.token, (obj) => {
          // 处理待办消息
          if (obj.type === "cldb") {
            this.updateDbsxNum(false);
            // 触发实时刷新待办数据
            EventBus.$emit("refreshBacklog");
            return;
          }
          // 刷新邮件消息条数
          if (obj.type === "clyj") {
            this.updateEmailNum();
            return;
          }
          if (obj.type === "znxx") {
            // 获取用户的站内消息
            getNetWorkNum().then(({ result }) => {
              let netMessageNum = result || 0;
              this.setNetMessageNum(netMessageNum);
            });
            return;
          }
          let url = obj.url;
          if (obj.toFromUnid != null && url != null) {
            if (obj.url.indexOf("?") > -1) {
              url = url + "&unid=" + obj.toFromUnid;
            } else {
              url = url + "?unid=" + obj.toFromUnid;
            }
          }
          // 获取用户的站内消息
          getNetWorkNum().then(({ result }) => {
            let netMessageNum = result || 0;
            this.setNetMessageNum(netMessageNum);
          });

          BlogMessage({
            msg: obj.content,
            title: "消息提醒",
            event: obj.moduleEvent,
            url: url,
            logUnid: obj.logUnid,
          });
        });

        // 获取用户的站内消息
        getNetWorkNum().then(({ result }) => {
          let netMessageNum = result || 0;
          this.setNetMessageNum(netMessageNum);
        });
      }

      // 获取当前登录人的代表事项
      if (
        window.HC_config.VUE_APP_isShowDBSX ||
        window.HC_config.VUE_APP_isShowYBSX
      ) {
        // 每10秒获取一次代表事项
        starTimer(() => {
          this.updateDbsxNum(true);
        });
      }

      // 获取当前登录人的未读邮件
      if (window.HC_config.VUE_APP_isShowEmail) {
        const { result } = await getEmailList({});
        result && this.setEmailNum(result.count);
      }

      // 获取阅文意见修改设置
      if (window.HC_config.VUE_APP_isShowYwOpinion) {
        const res = await getSetting();
        this.setYwyjxgSetting(res.result || {});
      }

      try {
        const response = await getInfo();
        this.setInfo(response.result);
        this.setRoles(response.result.roleKey);
        // 是否登录成功自动打卡
        if (window.HC_config.VUE_USE_ZDDK) {
          let par = {
            personId: response.result.unid,
            personName: response.result.personCommonname,
          };
          await zddk(par);
        }
        // 获取当前登录人需处理合同文件
        if (window.HC_config.VUE_APP_isShowHtgl) {
          await this.updateHtglNum(true);
        }
        if (window.HC_config.VUE_APP_isShowGxrz) {
          await this.updateGxrz(true);
        }
        // 更加unid查询缓存,如果存在则使用缓存。不存在使用用户的
        let currentPostUnid = localStorage.getItem(
          "postUnid_" + this.info.unid
        );
        if (currentPostUnid != null) {
          this.setCurrentPost(currentPostUnid);
        }

        return response;
      } catch (error) {
        throw error;
      }
    },
    // 登出
    async LogOut() {
      this.setToken(null);
      this.setInfo(null);
      this.setCurrentOrgUnid(null);
      this.setCurrentPost(null);
      // 退出登录关闭websocket
      if (window.HC_config.VUE_OPEN_WEBSOCKET) {
        websocket.closeWebSocket();
      }
      // 退出判断是否是单点登录进来的，若是则通知认证系统也退出
      let ssoToken = getSSOToken();
      console.log(ssoToken, "================单点登录退出==================");
      if (
        window.HC_config.VUE_IS_SSO &&
        window.HC_config.VUE_APP_SSO_LOGOUT_NOTIFY &&
        ssoToken
      ) {
        try {
          await logoutBySsoCode({ access_token: ssoToken });
          console.log("================单点登录退出成功==================");
          removeSSOToken();
        } catch (err) {
          console.error(err);
        }
      }
    },
    // 前端 登出
    async FedLogOut() {
      this.setToken(null);
      this.setInfo(null);
      // 退出登录关闭websocket
      if (window.HC_config.VUE_OPEN_WEBSOCKET) {
        websocket.closeWebSocket();
      }
    },
  },
});
